const mongoose = require("mongoose");
var New = require('../models/news.model');
var Comment =require('../models/comment.model');
//const async=require('async);
//增加
exports.create = function(req, res, next) {
        const news = new New(req.body);
        news.save().then((data) => res.json(data));
    }
    //更改
exports.update = function(req, res, next) {
        var id = req.params.id;
        New.findByIdAndUpdate(id, { $set: req.body }, { new: false, upsert: false }).then((data) => res.json(data));
    }
    //根据id删除单条记录
exports.delete = function(req, res, next) {
        var id = req.params.id;
        New.findByIdAndDelete(id).then((data) => res.json(data));
    }
    //根据id删除多条记录
exports.deletes = function(req, res, next) {
        const ids = req.body.ids.split(',');
        if (ids.length > 0) {
            New.remove({ _id: { $in: ids } }).then(data => {
                res.json({ "message": "数据已成功删除!" });
            })
        }
    }
    //根据id查找
exports.selectbyId = function(req, res, next) {
        var id = req.params.id;
        New.findById(id).then((data) => res.json(data));
    }
    //分页
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 10;

    var selectbyother = {};
    if (req.body.name && req.body.name.trim().length > 0) {
        selectbyother = {
            "author": new RegExp(req.body.name, 'i')
        }
    }

    if (req.body.newsId && req.body.newsId.trim().length > 0) {
        selectbyother = {
            "newsId": req.body.newsId
        }
    }

    New.paginate(selectbyother, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;

       getCount(result).then(data=>{
           res.json(data);
       })
        //res.json(result);
    });

    async function getCount(result){
        for(let i=0;i<result.rows.length;i++){
            await Comment.count({newsId:result.rows[i]._id},function(err,count){
                result.rows[i].commentCount=count;
            })
        }
        return result;
    }
}
// async.map(result.rows, function(News,cb) {
      //   Comment.count({newsId: News._id},function(err,count){
      //     News.commentCount = count;
      //     cb(null,News)
      //   })
      // },function(err,results){
      //   delete result.docs;
      //   res.json(result);
      // });